<?php

/**
 * This is the model class for table "items".
 *
 * The followings are the available columns in table 'items':
 * @property integer $id
 * @property integer $code
 * @property string $short_description
 * @property string $long_description
 * @property integer $category_id
 * @property integer $type_id
 */
class Item extends CActiveRecord
{
	
	public $name;
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return Item the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'items';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('code, short_description, long_description, category_id, type_id', 'required'),
			array('category_id, type_id', 'numerical', 'integerOnly'=>true),
			array('code', 'length', 'max'=>15),
			array('short_description', 'length', 'max'=>30),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, code, short_description, long_description, category_id, type_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'itemType' => array(self::BELONGS_TO, 'ItemType', 'type_id'),
			'itemCategory' => array(self::BELONGS_TO, 'ItemCategory', 'category_id'),
			'itemQuantity' => array(self::HAS_ONE, 'ItemQuantity', 'item_id'),
			'components' => array(self::MANY_MANY, 'Item', 'bill_of_materials(item_id,component_id)'),
			'dependencyCount' => array(self::STAT, 'ItemDependency', 'item_id'),
			'itemCost' => array(self::HAS_ONE, 'ItemCost', 'item_id'),
			'quantity' => array(self::STAT, 'InventoryBatch', 'item_id', 'select'=>'sum(quantity_on_hand)')
		);
	}
	
	public function buildListData()
	{
		$criteria=new CDbCriteria;
		$criteria->select="id, concat_ws(' - ',code, short_description) as name";
		
		$model = self::model()->findAll($criteria);
		
		return self::model()->findAll($criteria);
	}
	
	public function getCost()
	{
		if ($this->itemCost->use_dependency_cost)
		{
			$cost = $this->getDependencyCost($this);
		}
		else {
			$cost = $this->itemCost->cost;
		}
		
		return $cost;
	}
	
	public function getDependencyCost($item)
	{
		$total_cost = 0;

		foreach ($item->components as $component)
		{
	
			if ($component->itemCost->use_dependency_cost)
			{
				$cost = $this->getDependencyCost($component);
			}
			else {
				$cost = $component->itemCost->cost;
			}
			
			$quantity_needed = $this->getDependencyQuantity($item->id, $component->id);

			$total_cost += ($cost * $quantity_needed);

		}

		return $total_cost;
		
	}
	
	public function getDependencyQuantity($itemId, $componentId)
	{
		$criteria=new CDbCriteria;
		$criteria->select = 'quantity';
		$criteria->condition='item_id=:itemId and component_id=:componentId';
        $criteria->params=array(':itemId'=>$itemId,':componentId'=>$componentId);
        	
		$query = BillOfMaterials::model()->find($criteria);
			
		return $query->quantity;
	}
	
	public function getJsonItemCodeData()
	{
		$itemList = self::model()->findAll();
		
		foreach ($itemList as $item)
		{
			$item_codes[$item->id] = $item->code;
		}
		
		return json_encode($item_codes);
	}
	
	public function getJsonItemNameData()
	{
		$itemList = self::model()->findAll();
		
		foreach ($itemList as $item)
		{
			$item_names[$item->id] = $item->short_description;
		}
		
		return json_encode($item_names);
	}
	
	public function getJsonItemCostData()
	{
		$itemList = self::model()->findAll();
		
		foreach ($itemList as $item)
		{
			$item_costs[$item->id] = $item->getCost();
		}
		
		return json_encode($item_costs);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'code' => 'Code',
			'short_description' => 'Name',
			'long_description' => 'Description',
			'category_id' => 'Category',
			'type_id' => 'Type',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('code',$this->code);
		$criteria->compare('short_description',$this->short_description,true);
		$criteria->compare('long_description',$this->long_description,true);
		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('type_id',$this->type_id);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	/*
	public function behaviors()
	{ 
		return array( 'LoggableBehavior'=> 'application.modules.auditTrail.behaviors.LoggableBehavior', ); 
	}
	*/
	
}